package com.itcc.filter;

import com.itcc.entity.User;
import com.itcc.service.UserService;
import com.itcc.service.impl.UserServiceImpl;
import com.itcc.utils.Base64Utils;
import com.itcc.utils.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebFilter("/login.jsp")
public class AutoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            String content = null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Constants.AUTO_USER)) {
                    content = cookie.getValue();
                    break; // 找到后就跳出循环
                }
            }
            if (content != null) {
                content = Base64Utils.decode(content);

                // 检查分割后的数组长度，避免ArrayIndexOutOfBoundsException
                String[] split = content.split(Constants.FLAG);
                if (split.length > 1) {
                    String username = split[0];
                    String password = split[1];

                    UserService userService = new UserServiceImpl();
                    try {
                        User user = userService.login(username, password);
                        if (user != null) {
                            HttpSession session = request.getSession();
                            session.setAttribute("loginUser", user);
                            HttpServletResponse response = (HttpServletResponse) servletResponse;
                            response.sendRedirect(request.getContextPath() + "/index.jsp");
                        } else {
                            // 用户登录失败的处理逻辑
                            filterChain.doFilter(servletRequest, servletResponse);
                        }
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    // 分割后数组长度不足，可能是Cookie内容不正确或过期
                    // 可以记录日志或做其他错误处理
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
